﻿/*c1. 为示例（参见第4章课件第9页）中的泛型链表类添加类似于List<T>类的ForEach(Action<T> action)方法。
 通过调用这个方法打印链表元素，求最大值、最小值和求和（使用lambda表达式实现）。*/
using System;

class Node<T>
{
    public T Data { get; set; }
    public Node<T> Next { get; set; }

    public Node(T data)
    {
        Data = data;
        Next = null;
    }
}

class LinkedList<T>
{
    private Node<T> head;

    public void Add(T data)
    {
        Node<T> newNode = new Node<T>(data);
        if (head == null)
        {
            head = newNode;
        }
        else
        {
            Node<T> current = head;
            while (current.Next != null)
            {
                current = current.Next;
            }
            current.Next = newNode;
        }
    }

    public void ForEach(Action<T> action)
    {
        Node<T> current = head;
        while (current != null)
        {
            action(current.Data);
            current = current.Next;
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        LinkedList<int> list = new LinkedList<int>();
        list.Add(10);
        list.Add(20);
        list.Add(30);

        Console.WriteLine("链表元素：");
        list.ForEach(item => Console.Write(item + " "));
        Console.WriteLine();

        int sum = 0;
        int min = int.MaxValue;
        int max = int.MinValue;

        list.ForEach(item =>
        {
            sum += item;
            if (item < min)
                min = item;
            if (item > max)
                max = item;
        });

        Console.WriteLine($"最小值：{min}");
        Console.WriteLine($"最大值：{max}");
        Console.WriteLine($"总和：{sum}");

        Console.ReadLine();
    }
}
